import { mapState, mapMutations } from 'vuex'

import { events } from "@utils";
// import { createNewBlock } from '@utils/editor-config'

let curComponent = null;
let simulatorRef = null; // 画布dom
const dragenter = (e) => {
    e.dataTransfer.dropEffect = 'move';
}
const dragover = (e) => {
    e.preventDefault();
}
const dragleave = (e) => {
    e.dataTransfer.dropEffect = 'none';
}

export function menuBlockDraggerMixin() {
    return {
        computed: {
            ...mapState('editor', {
                curBlocks: state => state.curBlocks,
            }),
        },
        methods: {
            ...mapMutations('editor', [
                'addCurBlock'
            ]),
            mDrop(e) {
                this.addCurBlock({
                    // ...createNewBlock(curComponent),
                    ...curComponent,
                    styles: {
                        top: e.offsetY + 'px',
                        left: e.offsetX + 'px',
                    }
                })
                // 清除缓存
                curComponent = null;
            },
            mDragstart(e, component) {
                // dragenter进入元素中添加一个移动标识
                // dragouver在目标元素经过 必须要组织默认行为 否则不能触发drop
                // dragleave 离开元素的时候需要增加一个禁用标识
                // drop 松手的时候根据拖拽的组件 添加一个组件
                if (!simulatorRef) {
                    simulatorRef = document.getElementById('simulator-editor');
                }
                simulatorRef.addEventListener('dragenter', dragenter);
                simulatorRef.addEventListener('dragover', dragover);
                simulatorRef.addEventListener('dragleave', dragleave);
                simulatorRef.addEventListener('drop', this.mDrop);
                curComponent = component;
                // 发布end
                events.emit('start');
            },
            mDragend(e) {
                // simulatorRef = document.getElementById('simulator-editor');
                simulatorRef.removeEventListener('dragenter', dragenter);
                simulatorRef.removeEventListener('dragover', dragover);
                simulatorRef.removeEventListener('dragleave', dragleave);
                simulatorRef.removeEventListener('drop', this.mDrop);
                // 发布end
                events.emit('end');
            }
        }
    }
}
